/*
 * Copyright (C) 2022. Uber Technologies
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.uber.rib.core

import android.app.Application
import com.uber.autodispose.ScopeProvider
import com.uber.autodispose.lifecycle.LifecycleEndedException
import com.uber.rib.core.internal.CoroutinesFriendModuleApi
import io.reactivex.CompletableObserver
import io.reactivex.disposables.Disposable
import java.util.WeakHashMap
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext
import kotlin.reflect.KProperty
import kotlinx.coroutines.CoroutineName
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.job

/**
 * [CoroutineScope] tied to this [ScopeProvider]. This scope will be canceled when ScopeProvider is
 * completed
 *
 * This scope is bound to
 * [RibDispatchers.Main.immediate][kotlinx.coroutines.MainCoroutineDispatcher.immediate].
 *
 * Calling this property outside of the lifecycle of the [ScopeProvider] will throw
 * [OutsideScopeException][com.uber.autodispose.OutsideScopeException]. By setting
 * [RibCoroutinesConfig.shouldCoroutineScopeFailSilentlyOnLifecycleEnded] to `true`, accessing this
 * property after the [ScopeProvider] has completed will instead return a [CoroutineScope] that is
 * immediately cancelled.
 */
@OptIn(CoroutinesFriendModuleApi::class)
public val ScopeProvider.coroutineScope: CoroutineScope by LazyCoroutineScope {
  val context = createCoroutineContext()
  try {
    ScopeProviderCoroutineScope(this, context)
  } catch (e: LifecycleEndedException) {
    if (RibCoroutinesConfig.shouldCoroutineScopeFailSilentlyOnLifecycleEnded) {
      CoroutineScope(context).also {
        it.cancel("ScopeProvider is outside of scope. context = $context", e)
      }
    } else {
      throw e
    }
  }
}

/**
 * [CoroutineScope] tied to this [Application]. This scope will not be cancelled, it lives for the
 * full application process.
 *
 * This scope is bound to
 * [RibDispatchers.Main.immediate][kotlinx.coroutines.MainCoroutineDispatcher.immediate]
 */
@OptIn(CoroutinesFriendModuleApi::class)
public val Application.coroutineScope: CoroutineScope by LazyCoroutineScope {
  CoroutineScope(createCoroutineContext())
}

private fun Any.createCoroutineContext() =
  SupervisorJob() +
    RibDispatchers.Main.immediate +
    CoroutineName("${this::class.simpleName}:coroutineScope") +
    (RibCoroutinesConfig.exceptionHandler ?: EmptyCoroutineContext)

private class ScopeProviderCoroutineScope(
  scopeProvider: ScopeProvider,
  coroutineContext: CoroutineContext,
) :
  ScopeProvider by scopeProvider,
  CoroutineScope by CoroutineScope(coroutineContext),
  CompletableObserver {

  init {
    requestScope().subscribe(this)
  }

  override fun onSubscribe(d: Disposable) {
    coroutineContext.job.invokeOnCompletion { d.dispose() }
  }

  override fun onComplete() {
    cancel()
  }

  override fun onError(e: Throwable) {
    cancel("ScopeProvider completed with error", e)
  }
}

@CoroutinesFriendModuleApi
public class LazyCoroutineScope<This : Any>(private val initializer: This.() -> CoroutineScope) {
  public companion object {
    private val values = WeakHashMap<Any, CoroutineScope>()

    // Used to get and set Test overrides from rib-coroutines-test utils
    public operator fun get(provider: Any): CoroutineScope? = values[provider]
    public operator fun set(provider: Any, scope: CoroutineScope?) {
      values[provider] = scope
    }
  }
  public operator fun getValue(thisRef: This, property: KProperty<*>): CoroutineScope =
    synchronized(LazyCoroutineScope) {
      return values.getOrPut(thisRef) {
        thisRef.initializer().apply {
          coroutineContext.job.invokeOnCompletion {
            synchronized(LazyCoroutineScope) { values.remove(thisRef) }
          }
        }
      }
    }
}
